<?php

class Dispatcher {
	
	private $_controller;
	private $_action;
	private $_params;
	private $_named;
	
	private static $_instance;
	public static function _getInstance() {
		if(!self::$_instance) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}
	
	public function getAction(){return $this->_action;}
	
	public static function dispatch() {
		$D = self::_getInstance();
		$D->_parseRequest();
		
		$to_eval = '$C = new ' . $D->_controller . '();';
		eval($to_eval);
		if(!method_exists($C, $D->_action)) {
			$D->_action = "error";
			$D->_params = array(1001);
		}
		
		$params = null;
		if($D->_params) {
			foreach ($D->_params as $param) {
				if(!preg_match('/^\d+$/', $param)) {
					$param = "'" . str_replace("'", "\\'", $param) . "'";
				}
				$params .= ", $param";
			}
			$params = preg_replace('/^,\s*/', "", $params);
		}
		$C->setDispatcher($D);
		$C->params = (Object)array(
			"controller" => $D->_controller,
			"action" => $D->_action,
			"named" => $D->_named
		);
		$to_eval = '$C->' . $D->_action . '(' . $params .');';
		unset($_GET["request"]);
		$C->data = array_merge($_GET, $_POST);
		$C->__before();
		eval($to_eval);
		$C->__after();
		
		if($C->autoRender && !$C->rendered) {
			$C->render();
		}
	}
	
	private function _parseRequest() {
		$request = explode("/", $_GET["request"]);
		foreach ($request as $k=>$req){
			if(strpos($req, ":")>0){
				list($name,$value)=explode(":", $req, 2);
				$this->_named[$name] = $value;
				unset($request[$k]);
			}
		}
		$request = array_values($request);
		
		$this->_controller = array_shift($request);
		$this->_controller = $this->_controller ? $this->_controller : "Controller";
		
		$this->_action = array_shift($request);
		$this->_action = $this->_action ? $this->_action : "layout";
				
		$this->_params = $request;
	}
}

?>